<style>
  #stripe-element {
    margin-bottom: 14px;
    min-height: 100px;
  }
</style>

<div id="stripe-form" style="position: relative; width: 100%">
  <div id="stripe-element"></div>
  <div id="stripe-button"></div>
  <div id="payment-message" style="margin-top: 14px;"></div>
</div>

<script language="javascript">
  $(function () {
    let elements;

    $.createPaymentCard({
      src: "https://js.stripe.com/v3/",
      button: "#stripe-button",
      form: "#stripe-form",
      async scriptSuccess() {
        // $.hideSkeleton("#stripe-element")
        const stripe = Stripe("pk_test_51MM13qIuSh5sFyYa8N2bdstTiCHqX0g9eX7XubgJmOgXhejBha1h05zmqkD8cDhgHf5k7lQmGHBM3lxwD8pPDTtS00qrJo0GvV");

        // 检查链接是否包含payment_intent_client_secret 验证返回状态
        const clientSecret = new URLSearchParams(window.location.search).get(
          "payment_intent_client_secret"
        );
        if (clientSecret) {
          const { paymentIntent } = await stripe.retrievePaymentIntent(clientSecret);

          switch (paymentIntent.status) {
            case "succeeded":
              await fetch("{$interfaceCallback}&id=" + paymentIntent.id, {
                method: "GET"
              })
              $.toast({container:"#payment-message",text:"Payment succeeded!"})
              parent.location.href = "{$successUrl}";
              break;
            case "processing":
              $.toast({container:"#payment-message",text:"Your payment is processing."})
              break;
            case "requires_payment_method":
              $.toast({container:"#payment-message",text:"Your payment was not successful, please try again."})
              break;
            default:
              $.toast({container:"#payment-message",text:"Something went wrong."})
              break;
          }
          return;
        }

        const options = {
          paymentMethodTypes: ['card'],
          mode: 'payment',
          currency: 'gbp',
          amount: 4127,
        };
        elements = stripe.elements(options);
        const paymentElement = elements.create("payment", {
          fields: {
            billingDetails: {
              address: 'never'
            }
          }
        });
        paymentElement.mount("#stripe-element");
      },
      async verified() {
        const { error: submitError } = await elements.submit();
        if (submitError) {
          return false;
        }
        return true

      },
      async submit({ showLoading, hideLoading }) {
        showLoading()
        const { clientSecret, msg } = await fetch("{$create}", {
          method: "POST",
          headers: { "Content-Type": "application/json" }
        }).then((r) => r.json())
        if (msg) {
          showMessage(msg);
          hideLoading();
          return
        }
        const { error } = await stripe.confirmPayment({
          elements,
          clientSecret,
          confirmParams: {
            return_url: "{$this->domain}/checkouts/payment/stripe/return?checkout_token={$order->checkout_token}&order_number={$order->order_number}&payment_id={$order->payment_id}&local_token={$this->token}",
            payment_method_data: {
              billing_details: {
                address: {
                  "city": "{$billingAddress['city']}",
                  "country": "{$billingAddress['country_code']}",
                  "line1": "{$billingAddress['address1']}",
                  "line2": "{$billingAddress['address2']}",
                  "postal_code": "{$billingAddress['zip']}",
                  "state": "{$billingAddress['province_code']}"
                }
              }
            }
          },
        });

        const error_code = ['testmode_charges_only', 'bank_account_declined', 'api_key_expired', 'platform_api_key_expired', 'bank_account_unusable', 'charge_exceeds_source_limit', 'expired_card', 'refer_to_customer'];
        if (error.type === "card_error" || error.type === "validation_error") {
          $.toast({container:"#payment-message",text:error.message})

        } else if (error_code.indexOf(error.code.toLowerCase()) > -1) {
          await fetch("{$errorCallback}&msg=" + error.code, { method: "GET" })
          $.toast({container:"#payment-message",text:"An unexpected error occured."})
        } else {
          $.toast({container:"#payment-message",text:"An unexpected error occured."})
        }
        hideLoading();
      }
    })
  })
  // let isABPayment = '{$this->isABPayment}';
  // const stripe = Stripe("{$this->payment->interface_type_param->key}");
  // let elements;
  // initialize();
  // checkStatus();

  // document
  //   .querySelector("#payment-form")
  //   .addEventListener("submit", handleSubmit);

  // // Fetches a payment intent and captures the client secret
  // async function initialize() {
  //   if (!isABPayment) {
  //     createAjaxLoading();
  //   } else {
  //     window.parent.postMessage({ type: "jhpayform", code: 100, data: "" }, '*');
  //   }
  //   setLoading(false);
  //   const options = {
  //     paymentMethodTypes: ['card'],
  //     mode: 'payment',
  //     currency: '{$currency}',
  //     amount: $payamount,
  //   };
  //   elements = stripe.elements(options);
  //   const paymentElement = elements.create("payment", {
  //     fields: {
  //       billingDetails: {
  //         address: 'never'
  //       }
  //     }
  //   });
  //   paymentElement.mount("#payment-element");

  //   paymentElement.on('ready', function (event) {
  //     // moi.removeLoading("#payment-form")
  //     document.querySelector("#submit").classList.remove("hidden");
  //   });
  //   if (!isABPayment) {
  //     removeAjaxLoading();
  //   } else {
  //     window.parent.postMessage({ type: "jhpayform", code: 200, data: "" }, '*');
  //   }
  // }

  // async function handleSubmit(e) {
  //   e.preventDefault();
  //   setLoading(true);
  //   const { error: submitError } = await elements.submit();
  //   if (submitError) {
  //     setLoading(false);
  //     return;
  //   }
  //   const { clientSecret, msg } = await fetch("{$create}", {
  //     method: "POST",
  //     headers: { "Content-Type": "application/json" }
  //   }).then((r) => r.json())
  //   if (msg) {
  //     showMessage(msg);
  //     setLoading(false);
  //     return
  //   }
  //   const { error } = await stripe.confirmPayment({
  //     elements,
  //     clientSecret,
  //     confirmParams: {
  //       return_url: "{$this->domain}/checkouts/payment/stripe/return?checkout_token={$order->checkout_token}&order_number={$order->order_number}&payment_id={$order->payment_id}&local_token={$this->token}",
  //       payment_method_data: {
  //         billing_details: {
  //           address: {
  //             "city": "{$billingAddress['city']}",
  //             "country": "{$billingAddress['country_code']}",
  //             "line1": "{$billingAddress['address1']}",
  //             "line2": "{$billingAddress['address2']}",
  //             "postal_code": "{$billingAddress['zip']}",
  //             "state": "{$billingAddress['province_code']}"
  //           }
  //         }
  //       }
  //     },
  //   });

  //   const error_code = ['testmode_charges_only', 'bank_account_declined', 'api_key_expired', 'platform_api_key_expired', 'bank_account_unusable', 'charge_exceeds_source_limit', 'expired_card', 'refer_to_customer'];

  //   if (error.type === "card_error" || error.type === "validation_error") {
  //     showMessage(error.message);
  //   } else if (error_code.indexOf(error.code.toLowerCase()) > -1) {
  //     await fetch("{$errorCallback}&msg=" + error.code, { method: "GET" })
  //     showMessage("An unexpected error occured.");
  //   } else {
  //     showMessage("An unexpected error occured.");
  //   }

  //   setLoading(false);
  // }

  // // Fetches the payment intent status after payment submission
  // async function checkStatus() {
  //   const clientSecret = new URLSearchParams(window.location.search).get(
  //     "payment_intent_client_secret"
  //   );

  //   if (!clientSecret) {
  //     return;
  //   }

  //   const { paymentIntent } = await stripe.retrievePaymentIntent(clientSecret);

  //   switch (paymentIntent.status) {
  //     case "succeeded":
  //       await fetch("{$interfaceCallback}&id=" + paymentIntent.id, {
  //         method: "GET"
  //       })
  //       showMessage("Payment succeeded!");
  //       parent.location.href = "{$successUrl}";
  //       break;
  //     case "processing":
  //       showMessage("Your payment is processing.");
  //       break;
  //     case "requires_payment_method":
  //       showMessage("Your payment was not successful, please try again.");
  //       break;
  //     default:
  //       showMessage("Something went wrong.");
  //       break;
  //   }
  // }

  // // ------- UI helpers -------

  // function showMessage(messageText) {
  //   const messageContainer = document.querySelector("#payment-message");

  //   messageContainer.classList.remove("hidden");
  //   messageContainer.textContent = messageText;

  //   setTimeout(function () {
  //     messageContainer.classList.add("hidden");
  //     messageText.textContent = "";
  //   }, 4000);
  // }

  // // Show a spinner on payment submission
  // function setLoading(isLoading) {
  //   if (isLoading) {
  //     // Disable the button and show a spinner
  //     document.querySelector("#submit").disabled = true;
  //     document.querySelector("#spinner").classList.remove("hidden");
  //     document.querySelector("#button-text").classList.add("hidden");
  //   } else {
  //     document.querySelector("#submit").disabled = false;
  //     document.querySelector("#spinner").classList.add("hidden");
  //     document.querySelector("#button-text").classList.remove("hidden");
  //   }
  // }
</script>